package com.caration.shell.action;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.support.v4.app.FragmentActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.caration.shell.R;

public class ActionProvider {
	public static ArrayList<HashMap<String, Object>> sAppsList = new ArrayList<HashMap<String, Object>>();
	public static ArrayList<HashMap<String, Object>> sShortcutList = new ArrayList<HashMap<String, Object>>();
	public static ArrayList<HashMap<String, Object>> sCustomCMDList = new ArrayList<HashMap<String, Object>>();
	public static ActionAdapter sShortcutAdapter;
	public static ActionAdapter sAppsLinkAdapter;
	public static ActionAdapter sCustomCMDAdapter;
	public static ActionSelector sSelector;
	public static Handler sUIHandler;
	private static Handler sBackHandler;
	private static HandlerThread sHandlerThread;

	public static ActionAdapter getListAdapter(int index) {
		ActionAdapter adapter = null;
		switch (index) {
		case 0:
			adapter = sAppsLinkAdapter;
			break;
		case 1:
			adapter = sCustomCMDAdapter;
			break;
		case 2:
			adapter = sShortcutAdapter;
			break;
		}
		return adapter;
	}

	public static void onDestroy() {
		clear();
		sUIHandler = null;
		sBackHandler = null;
		sHandlerThread.quit();
		sHandlerThread = null;
		sSelector = null;
	}

	public static void clear() {
		sAppsList.clear();
		sShortcutList.clear();
		sCustomCMDList.clear();
		sShortcutAdapter.clear();
		sShortcutAdapter = null;
		sAppsLinkAdapter.clear();
		sAppsLinkAdapter = null;
		sCustomCMDAdapter.clear();
		sCustomCMDAdapter = null;
	}

	public static void onItemClick(int id, int itemIndex) {
		HashMap<String, Object> hashmap = null;
		switch (id) {
		case 0:
			hashmap = sAppsList.get(itemIndex);
			break;
		case 1:
			hashmap = sCustomCMDList.get(itemIndex);
			break;
		case 2:
			hashmap = sShortcutList.get(itemIndex);
			break;
		}
		if (hashmap != null) {
			Intent intent = new Intent(sSelector.obtainIntent());
			if (id != 1) {
				String appName = (String) hashmap.get("appName");
				String pkgName = (String) hashmap.get("packageName");
				String clsName = (String) hashmap.get("className");
				if (pkgName == null || clsName == null) {
					intent.setAction(Intent.ACTION_CREATE_SHORTCUT);
					intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, appName);
				} else {
					intent.setClassName(pkgName, clsName);
				}
			} else {
				intent.putExtra("action", (Integer) hashmap.get("action"));
			}
			intent.putExtra("action_type", id);
			intent.putExtra("action_name", (String) hashmap.get("appName"));
			sSelector.setResult(FragmentActivity.RESULT_OK, intent);
			sSelector.finish();
			onDestroy();
		}
	}

	public static void init(ActionSelector context) {
		sSelector = context;
		sUIHandler = new Handler(Looper.getMainLooper());
		sHandlerThread = new HandlerThread("Action Database Operating");
		sHandlerThread.start();
		sBackHandler = new Handler(sHandlerThread.getLooper());
		initCMD(context);
		if (sAppsList.size() == 0) {
			sBackHandler.post(new AppsRunnable());
		}
		if (sShortcutList.size() == 0) {
			sBackHandler.post(new ShortcutsRunnable());
		}
		String from[] = { "icon", "appName" };
		int[] ids = { R.id.icon, R.id.appName };
		sShortcutAdapter = new ActionAdapter(context, sShortcutList, from, ids);
		sAppsLinkAdapter = new ActionAdapter(context, sAppsList, from, ids);
		sCustomCMDAdapter = new ActionAdapter(context, sCustomCMDList, from,
				ids);
	}

	private static ArrayList<HashMap<String, Object>> initCMD(Context context) {
		if (sCustomCMDList.size() == 0) {
			if (CommandsHelper.sCommands == null) {
				ArrayList<Command> arraylist = new ArrayList<Command>();
				arraylist.add(new Command(context, Command.CMD_NONE));
				arraylist.add(new Command(context, Command.CMD_APP_DRAWER));
				arraylist.add(new Command(context, Command.CMD_HOME_DESKTOP));
				arraylist.add(new Command(context,
						Command.CMD_SWITCH_DRAWER_HOME));
				arraylist.add(new Command(context, Command.CMD_TOGGLE_NOTIBAR));
				arraylist.add(new Command(context, Command.CMD_EXPAND_NOTIBAR));
				arraylist.add(new Command(context, Command.CMD_TOGGLE_MENU));
				arraylist.add(new Command(context, Command.CMD_EXPAND_MENU));
				arraylist.add(new Command(context, Command.CMD_TEXT_SEARCH));
				arraylist.add(new Command(context, Command.CMD_VOICE_SEARCH));
				arraylist.add(new Command(context, Command.CMD_SHELL_SETTING));
				CommandsHelper.sCommands = arraylist;
			}
			HashMap<String, Object> hashmap;
			for (Iterator<Command> iterator = CommandsHelper.sCommands
					.iterator(); iterator.hasNext(); sCustomCMDList
					.add(hashmap)) {
				hashmap = new HashMap<String, Object>();
				Command cmd = (Command) iterator.next();
				hashmap.put("icon",
						context.getResources().getDrawable(cmd.mIconResId));
				hashmap.put("appName", cmd.mName);
				hashmap.put("action", cmd.mActionId);
			}

			if (sCustomCMDAdapter != null)
				sCustomCMDAdapter.notifyDataSetChanged();
		}
		return sCustomCMDList;
	}

	static class AppsRunnable implements Runnable {

		@Override
		public void run() {
			PackageManager packagemanager = sSelector.getPackageManager();
			Intent intent = new Intent(Intent.ACTION_MAIN, null);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			List<ResolveInfo> list = packagemanager.queryIntentActivities(
					intent, PackageManager.SIGNATURE_MATCH);
			final ArrayList<HashMap<String, Object>> apps = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> hashmap;
			for (Iterator<ResolveInfo> iterator = list.iterator(); iterator
					.hasNext(); apps.add(hashmap)) {
				ResolveInfo resolveinfo = (ResolveInfo) iterator.next();
				hashmap = new HashMap<String, Object>();
				hashmap.put("icon",
						resolveinfo.activityInfo.loadIcon(packagemanager));
				hashmap.put("appName",
						resolveinfo.activityInfo.loadLabel(packagemanager));
				hashmap.put("packageName",
						resolveinfo.activityInfo.applicationInfo.packageName);
				hashmap.put("className", resolveinfo.activityInfo.name);
			}

			if (sAppsLinkAdapter != null) {
				sUIHandler.post(new Runnable() {

					@Override
					public void run() {
						sAppsList.addAll(apps);
						sAppsLinkAdapter.notifyDataSetChanged();
					}
				});
			}
		}
	}

	static class ShortcutsRunnable implements Runnable {

		@Override
		public void run() {
			PackageManager packagemanager = sSelector.getPackageManager();
			List<ResolveInfo> resolves = packagemanager.queryIntentActivities(
					new Intent(Intent.ACTION_CREATE_SHORTCUT),
					PackageManager.SIGNATURE_MATCH);
			Collections.sort(resolves, new ResolveInfo.DisplayNameComparator(
					packagemanager));
			final ArrayList<HashMap<String, Object>> shortcuts = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> hashmap;
			for (Iterator<ResolveInfo> iterator = resolves.iterator(); iterator
					.hasNext(); shortcuts.add(hashmap)) {
				ResolveInfo resolveinfo = iterator.next();
				hashmap = new HashMap<String, Object>();
				hashmap.put("icon",
						resolveinfo.activityInfo.loadIcon(packagemanager));
				hashmap.put("appName",
						resolveinfo.activityInfo.loadLabel(packagemanager));
				hashmap.put("packageName",
						resolveinfo.activityInfo.applicationInfo.packageName);
				hashmap.put("className", resolveinfo.activityInfo.name);
			}

			if (sShortcutAdapter != null) {
				sUIHandler.post(new Runnable() {

					@Override
					public void run() {
						sShortcutList.addAll(shortcuts);
						sShortcutAdapter.notifyDataSetChanged();
					}
				});
			}

		}
	}
}
